
//究其原因是因为阅读邮件的附件没有写成类，而此处算patch
var _Mail_Attachement = Class.create();
_Mail_Attachement.prototype = {
    initialize: function(){
    },
    initPage: function(){
    },
    loadAttPreView: function(){
        var imgUrl = "./mail/" + parseFloat(readMailName);
        if (mail_atts == null) 
            return;
        previewContent = "";
        mail_atts.each(function(mail){
            attsize = mail.size < 1024 ? "1.0k" : strfsize(mail.size);
            if (mail.preview_img_url != "") {
                previewContent += '<ol><div class="view"><a href="' + imgUrl + mail.preview_url_direct + '" target="_blank"><img src="' + imgUrl + mail.preview_img_url + '" /></a></div>' +
                '<div class="view"> <li><span>' +
                mail.name +
                ' </span>(' +
                attsize +
                ')</li><li><a href="' +
                imgUrl +
                mail.url +
                '">下载</a></li></div></ol>';
                
            }
            else 
                if (mail.preview_url != "") {
                    var q = (mail.name).split(".");
                    var type = (q[q.length - 1]).toLowerCase();
                    attsize = mail.size < 1024 ? "1.0k" : strfsize(mail.size);
                    type = isKnow(type);
                    previewContent += '<ol><div class="view"><img src="' + MailConst.IMG + "/type/" + type + '.gif" /></div>' +
                    '<div class="view"> <li><span>' +
                    mail.name +
                    ' </span>(' +
                    attsize +
                    ')</li><li><a href="' +
                    imgUrl +
                    mail.preview_url +
                    '" target="_blank" class="">预览</a><a href="' +
                    imgUrl +
                    mail.url +
                    '">下载</a></li></div></ol>';
                }
                else {
                    var q = (mail.name).split(".");
                    var type = (q[q.length - 1]).toLowerCase();
                    attsize = mail.size < 1024 ? "1.0k" : strfsize(mail.size);
                    type = isKnow(type);
                    previewContent += '<ol><div class="view"><img src="' + MailConst.IMG + "/type/" + type + '.gif" /></div>' +
                    '<div class="view"> <li><span>' +
                    mail.name +
                    ' </span>(' +
                    attsize +
                    ')</li><a href="' +
                    imgUrl +
                    mail.url +
                    '">下载</a></li></div></ol>';
                }
        });
        $('read_att_pre').update(previewContent);
        if (previewStatus == false) {
            preview_controller(0);
        }
    },
    saveAll2UDisk: function(){
        if (mail_atts.length == 1) {
            this.save2UDisk(mail_atts[0].offset, readMailName);
            return;
        }
        var t = new Template(Save2UDiskListTemplate);
        var data = new Array;
        data["tr_inlines"] = "";
        mail_atts.each(function(mail){
            var q = "";
            q = '<tr>' +
            '<td><input onclick="udisk.notAll( ' +
            mail.offset +
            ' );" class="SelectorHelper" type="checkbox" name="checkbox" value="checkbox" /><input type="hidden" class="SelectValueHelper" value="' +
            mail.offset +
            '"/></td>' +
            '<td>' +
            mail[0] +
            '</td>' +
            '</tr>'
            data["tr_inlines"] += q;
        });
        CreateFullPageMask("read");
        Element.insert($('sohuMailMain'), {
            bottom: t.evaluate(data)
        });
        var screen = getWindowDimensions();
        var _x = parseInt(screen.win_width - 600) / 2;
        var _y = parseInt(screen.win_height - 300) / 3;
        $('save2DiskSelector').setStyle({
            left: _x + "px",
            top: _y + "px"
        });
        //$( 'AllSelector' ).observe( 'change', mailAttchement.AllSelectAct.bind( mailAttchement ) );
        $('AllSelector').observe('click', mailAttchement.AllSelectAct.bind(mailAttchement));
    },
    AllSelectAct: function(){
        if ($('AllSelector').checked) {
            //逻辑全选
            var tr_lists = $('save2DiskSelector').getElementsByClassName('SelectorHelper');
            if (tr_lists.length > 0) {
                for (var i = 0; i < tr_lists.length; i++) {
                    var q = tr_lists[i];
                    q.checked = true;
                }
            }
        }
        else {
            //完全反选
            var tr_lists = $('save2DiskSelector').getElementsByClassName('SelectorHelper');
            if (tr_lists.length > 0) {
                for (var i = 0; i < tr_lists.length; i++) {
                    var q = tr_lists[i];
                    q.checked = false;
                }
            }
        }
        
    },
    cancelSaveAll: function(){
        if ($('save2DiskSelector')) {
            $('save2DiskSelector').remove();
        }
        try {
            _dialog.closeCustom();
        } 
        catch (e) {
        }
        try {
            $('prompt_panel').remove();
        } 
        catch (e) {
        }
    },
    saveToUDisk: function(mid, isAll){
        mid = mid + "." + ((isAll === false) ? G.EXT_SAVESINGLETOUDISK : G.EXT_SAVEALLTOUDISK) + "." + G.UDISK_SERVERID;
        var params = {
            mid: mid
        };
        saveToUdisk(params, this.save2UdiskCallBack.bind(this), this.save2UdiskFailed.bind(this));
    },
    save2UDisk: function(_offset, _mailId){
        var params = {
            offset: pa.toJSON(),
            mailid: _mailId
        };
        att_save2Udisk(params, this.save2UdiskCallBack.bind(this), this.save2UdiskFailed.bind(this));
    },
    save2UdiskCallBack: function(ret){
        var title = "保存成功";
        var info = "已保存到网络U盘：<br/>临时存储区/邮件附件/<br/>点【确定】进入U盘查看<br/>点【取消】关闭该窗口";
        if (ret.status != 0) {
            title = "保存失败";
            info = "点【确定】进入U盘查看；点【取消】关闭该窗口";
        }
        
        
        _dialog.confirm({
            title: title,
            info: info,
            click: function(){
                window.open("http://u.sohu.com/main.action?folderId=-3");
            }
        });
        
    },
    saveAll2UDiskSubmit: function(){
        var flag = 0;
        var tr_lists = $('save2DiskSelector').getElementsByClassName('SelectorHelper');
        var value_lists = $('save2DiskSelector').getElementsByClassName('SelectValueHelper');
        var offsets = new Array();
        for (var i = 0; i < tr_lists.length; i++) {
            if (tr_lists[i].checked) {
                flag = flag + 1;
                var v = value_lists[i].value;
                offsets.push(v);
            }
        }
        if (flag == 0) {
            this.cancelSaveAll();
            return false;
        }
        var params = {
            offset: offsets.toJSON(),//偏移量的Array
            mailid: readMailName//mailID这个用于标志邮件
        }
        att_save2Udisk(params, this.save2UdiskCallBack.bind(this), this.save2UdiskFailed.bind(this));
    },
    save2UdiskFailed: function(){
        alert('网络错误，请稍后再试！');
    }
};

var mailAttchement = new _Mail_Attachement();




/*
 这个类是控制U盘信息的
 */
var UDisk = Class.create();
UDisk.prototype = {
    initialize: function(){
        this.folderdata = '';
        this.groupdata = Object();
        this.datam = Object();
        this.res = [];
        this.hasori = -1;
        this.firstFolder = 0;
    },
    getList: function(){
        if (ExecFunc("udiskRightsFilter") === false) {
            return false;
        }
        var param = null;
        getUDiskAllList(param, this.getAllListSuccess.bind(this), this.getAllListFailed.bind(this));
        
    },
    getAllListSuccess: function(ret){
        try {
            if (!isNaN(ret["status"]) && parseInt(ret["status"]) == -6) {
                _dialog.alert({
                    info: "<div align='center'>您的网络U盘尚无存储文件！<br/>" +
                    "<a class='orange' target='_blank' href='http://u.sohu.com' style='text-decoration:underline;' onclick='try{POPDIV.style.display=POPDIVSHADOW.style.display=\"none\";}catch(e){}'>登录</a>U盘</div>"
                });
                return false;
            }
        } 
        catch (e) {
        }
		
			this.folderdata = '';
			this.groupdata = Object();
			this.datam = Object();
			this.res = [];
			this.folderdata = ret.userfolder_list;
		try {
			this.groupData();
		} catch(e) {}
		try {
			this.sortData();
		} catch(e) {}
		try {
			this.draw_single_node(0);
		} catch(e) {}
		try {
			this.displayPanel();
		} catch(e) {}
		
        
    },
    TreeDisplay: function(){
        var _display = '';
        this.res.each(function(item){
            if (item.depth == 1) {
                _display += '</ul><ul ><img align="absmiddle" src="' + MailConst.ALL + '/minus1.gif" />' +
                '<a class="udiskitemHelper" id="udisktreeitem_' +
                item.id +
                '" href="javascript:;" onclick="udisk.getSingleDir(' +
                item.id +
                ');return false;">' +
                item.foldername +
                '</a>';
            }
            else {
                _display += '<li class="udiskitemHelper" id="udisktreeitem_' + item.id + '" style="white-space: nowrap;" ><img align="absmiddle" src="' + MailConst.ALL + '/spacer.gif" align="absmiddle" class="am icon-default" width="20px"/>' +
                '<a href="javascript:;" onclick="udisk.getSingleDir(' +
                item.id +
                ');return false;">' +
                item.foldername +
                '</a></li>';
            }
        });
        _display = _display.substr(5);
        _display += "</ul>";
        return _display;
    },
    getSingleDir: function(id){
        var param = {
            folderid: id
        }
        getUDiskList(param, this.getListSuccess.bind(this), this.getListFailed.bind(this));
    },
    getListSuccess: function(ret){
        var filelists = ret.userfile_list;
        var userinfo = USERINFO.evalJSON();
        if (filelists.length == 0) {
            $('tablearea').update("当前文件夹没有文件");
            return;
        }
        else {
            var tmpuserFlag = false;
            if (udisk.ispermanent(ret.folderid)) {
                tmpuserFlag = true;
            }
            var _display = '' +
            '<table  cellpadding="0" cellspacing="1" id="mailfolder" style="width:80%"><tr>' +
            '<th width="30px" align="center"><input type="checkbox" id="fileAllSelector" name="checkbox2" value="checkbox" /></th>' +
            '<th>名称</th>' +
            '<th width="50px" align="center">文件类型</th>' +
            '<th width="50px" align="right">大小</th>' +
            '<th width="100px" align="center">有效期</th>' +
            '</tr>';
            filelists.each(function(item){
                var _filesplits = item.filename.split(".");
                var _filename = '';
                for (var i = 0; i < _filesplits.length - 1; ++i) {
                    _filename += _filesplits[i];
                }
                var _filefix = _filesplits[_filesplits.length - 1];
                var _hid_value = item.fileid + "|" + item.expiretime.split(" ")[0] + "|" + item.filename;
                
                _display += '<tr><td><input class="uFileSelectorHelper" onclick="udisk.notAll(\'' + "" + _hid_value + '\');" type="checkbox" name="checkbox" value="checkbox" /></td>' +
                '<td>' +
                '<input type="hidden" value="' +
                _hid_value +
                '" class="uFileHiddenhelper" />' +
                _filename +
                '</td>' +
                '<td>' +
                _filefix +
                '</td>' +
                '<td style="text-align:right;">' +
                parseInt(item.filesize / 1024) +
                ' KB</td>';
                if (tmpuserFlag) {
                    _display += '<td>同手机邮件取消日</td></tr>';
                }
                else {
                    _display += '<td>' + item.expiretime.split(" ")[0] + '</td></tr>';
                }
                
            });
            _display += "</table>";
            $('tablearea').update(_display);
            $('fileAllSelector').observe('click', this.selectAllFile.bind(this));
            
        }
    },
    notAll: function(value){
        var tr_lists = new Array();
        var value_lists = new Array();
        try {
            tr_lists = $('tablearea').getElementsByClassName('uFileSelectorHelper');
            value_lists = $('tablearea').getElementsByClassName('uFileHiddenhelper');
        } 
        catch (e) {
        }
        if (tr_lists.length == 0) {
            try {
                tr_lists = $('mailfolder').getElementsByClassName('SelectorHelper');
                value_lists = $('mailfolder').getElementsByClassName('SelectValueHelper');
            } 
            catch (e) {
            }
        }
        var counts = 0;
        var flag = false;
        if (parseInt(tr_lists.length) > 0) {
            for (var i = 0; i < tr_lists.length; i++) {
                if ((value_lists[i]).value == value) {
                    if (!tr_lists[i].checked) {
                        counts = -1;
                    }
                    flag = tr_lists[i].checked;
                    //var q = tr_lists[ i ];
                    //q.checkd = q.checked == true ? false : true;
                }
            }
        }
        if (counts < 0) {
            try {
                $('fileAllSelector').checked = false;
                tr_lists[i].checked = flag;
            } 
            catch (e) {
            }
            try {
                $('AllSelector').checked = false;
                tr_lists[i].checked = flag;
            } 
            catch (e) {
            }
        }
        
    },
    submitSelect: function(){
        var str_prefix = "<div id='UDiskPanel'><br /><br /><br /><br /><br /><br /><br /><br /><br />-----（下面的连接是您的朋友通过" + USE_SYS.title + "网络U盘给您的共享附件，您可下载）";
        if (this.hasori < 0) {
            //初始化的时候，如果能检测到ori,那么就检测是否有UDiskPanel标签，有的话，干掉，没有的话，置另外一个标志符
            if (Editor.c().document.getElementById('ori') && Editor.c().document.getElementById('UDiskPanel')) {
                Editor.c().document.getElementById('UDiskPanel').id = '';
                str_prefix = "<div id='UDiskPanel'><br /><br />-----（下面的连接是您的朋友通过" + USE_SYS.title + "网络U盘给您的共享附件，您可下载）";
            }
            else 
                if (Editor.c().document.getElementById('ori')) {
                    str_prefix = "<div id='UDiskPanel'><br /><br />-----（下面的连接是您的朋友通过" + USE_SYS.title + "网络U盘给您的共享附件，您可下载）";
                }
            this.hasori = 1;
        }
        
        var value_lists = $('tablearea').getElementsByClassName('uFileHiddenhelper');
        var tr_lists = $('tablearea').getElementsByClassName('uFileSelectorHelper');
        var str_postfix = "</div>";
        var str_display = '';
        var counts = 0;
        if (tr_lists.length > 0) {
            for (var i = 0; i < tr_lists.length; i++) {
                var q = tr_lists[i];
                if (q.checked) {
                    counts = counts + 1;
                    var fileid = (value_lists[i].value.split("|"))[0];
                    var fileexpire = (value_lists[i].value.split("|"))[1];
                    var filename = (value_lists[i].value.split("|"))[2];
                    str_display += "<br />" + filename + "  ";
                    str_display += "<a target='_blank' href='http://u.sohu.com/download/" + G.UDISK_SERVERID + "/" + fileid + "'>http://u.sohu.com/download/" + G.UDISK_SERVERID + "/" + fileid + "</a>   文件有效期至：";
                    if ((fileexpire + "").strip() == "2020-01-01") {
                        fileexpire = "同手机邮件取消日";
                    }
                    str_display += fileexpire;
                }
            }
            //Alva.Notice 这里我想拿到编辑框中的div
            var panelObj = Editor.c().document.getElementById('UDiskPanel');
            if (!panelObj && counts > 0) {
            
                var content = writemail.getContentInput();
                //恶心的代码，专门为转发做patch
                if (this.hasori > 0) {
                    //追加前面
                    str_display = str_prefix + str_display + str_postfix + content;
                    //str_display = content + str_prefix + str_display + str_postfix;
                }
                else {
                    //追加后面
                    str_display = content + str_prefix + str_display + str_postfix;
                }
                writemail.setContentInput(str_display);
            }
            else 
                if (counts > 0) {
                    try {
                        //new Insertion.Bottom( panelObj, str_display );
                        panelObj.innerHTML += str_display;
                    } 
                    catch (e) {
                        alert(e)
                    }
                }
        }
        this.removeMask();
        
    },
    selectAllFile: function(){
        if ($('fileAllSelector').checked) {
            //逻辑全选
            var tr_lists = $('tablearea').getElementsByClassName('uFileSelectorHelper');
            if (tr_lists.length > 0) {
                for (var i = 0; i < tr_lists.length; i++) {
                    var q = tr_lists[i];
                    q.checked = true;
                }
            }
        }
        else {
            //完全反选
            var tr_lists = $('tablearea').getElementsByClassName('uFileSelectorHelper');
            if (tr_lists.length > 0) {
                for (var i = 0; i < tr_lists.length; i++) {
                    var q = tr_lists[i];
                    q.checked = false;
                }
            }
        }
    },
    getListFailed: function(){
        alert('读取U盘列表错误！');
    },
    displayPanel: function(){
        var self = this;
        var t = new Template(UDiskTreeTemplate);
        var data = {};
		
		/*
		try {
			CreateFullPageMask();
		} catch(e) {}
        
		try {
			//创建IE下的遮罩层
			var frame_div = '<div id="frameHolder" style="position: absolute;width:660px;height:400px; z-index:9998;"></div>';
			if (!$('frameHolder')) 
				new Insertion.Bottom(document.body, frame_div);
			var tmpframe = document.createElement("iframe");
			tmpframe.setAttribute("id", "ulist_frame");
			tmpframe.setAttribute("name", "ulist_frame");
			tmpframe.setAttribute("frameborder", 0, 0);
			tmpframe.setAttribute("scrolling", "no");
			tmpframe.setAttribute("width", "800");
			tmpframe.setAttribute("height", "440");
			tmpframe.setAttribute("z-index", "9998");
			$('frameHolder').appendChild(tmpframe);
			console.log(data);
			Element.insert(document.body, {
				bottom: t.evaluate(data)
			});
		} catch(e) {}
        //Element.insert( $( 'sohuMailMain' ), {bottom : t.evaluate( data ) } );
		try {
			var screen = getWindowDimensions();
			var _x = parseInt(screen.win_width - 600) / 2;
			var _y = parseInt(screen.win_height - 300) / 3;
			$('TreeRootDiv').setStyle({
				left: _x + "px",
				top: _y + "px"
			});
			
			$('frameHolder').setStyle({
				left: _x + "px",
				top: _y + "px"
			});
		} catch(e) {}
        //this.getSingleDir( -2 );
		*/
		
		_dialog.custom({
			html: new Template(UDiskTreeTemplate).evaluate(data),
			style: {width:'800px', height:'400px', backgroundColor:'white'},
			dragid: 'drag_bar'
		});
        
		try {
			var tree = new BTree(this.res, {
				//sysFolder:'/images/icon_fujian.gif',
				selctedColor: 'white',
				selectedBg: '#3a84d5',
				folderClosed: MailConst.ALL + '/tree/folderClosed.gif',
				folderOpen: MailConst.ALL + '/tree/folderOpen.gif',
				//plus:MailConst.ALL+"/tree/plus1.gif",
				//minus:MailConst.ALL+"/tree/minus1.gif",
				imgDir: MailConst.ALL + "/tree/",
				itemClass: "BTREE_ITEM_CLASS",
				lineClass: "TREE_LINECLASS",
				tagKey: "filecount",
				nameLength: 14,
				dirLine: true,
				clickHandler: function(id){
					self.getSingleDir(id);
				}
			});
		} catch(e) {}
		try {
			tree.build('udisk_dir_tree');
			tree.clickById(-2);
		} catch(e) {}
        
    },
    removeMask: function(){
        if ($('TreeRootDiv')) {
            $('TreeRootDiv').remove();
        }
        if ($('frameHolder')) {
            $('frameHolder').remove();
        }
		try {
			_dialog.closeCustom();
		} catch(e) {}
    },
    getAllListFailed: function(){
        alert('读取U盘文件列表错误!');
    },
    /*
     Amazing Functions Start
     */
    groupData: function(){
        var m = this.folderdata;
        this.groupdata = null;
        this.groupdata = Object();
        for (var i = 0; i < m.length; i++) {
            if (this.groupdata[m[i].parentid] == null || this.groupdata[m[i].parentid] == undefined) {
                this.groupdata[m[i].parentid] = new Array()
            }
            (this.groupdata[m[i].parentid]).push(m[i]);
        }
    },
    sortData: function(){
        this.datam = null;
        this.datam = Object();
        var m = this.folderdata;
        var databack = m.clone();
        var newdata = databack.sort(function(a, b){
            if (parseInt(a.id) == parseInt(b.id)) {
                return 0;
            }
            else {
                return parseInt(a.id) > parseInt(b.id) ? 1 : -1;
                //return parseInt( a.id ) > parseInt( b.id ) ? 1 : -1;
            }
        });
        this.folderdata = newdata;
        this.datam = newdata;
    },
    draw_single_node: function(id, depth){
        var m = this.folderdata;
        if (depth == null || depth == undefined) 
            depth = 0;
        var subs = this.groupdata[parseInt(id)];
        var current_node = this.getNodeById(id);
        if (current_node != null) {
            current_node["depth"] = depth;
            this.res.push(current_node);
        }
        if (subs == null || subs.length == 0) {
            return 1;
        } else {
            depth = depth + 1;
            for (var ti = 0; ti < subs.length; ti++) {
                this.draw_single_node(subs[ti].id, depth);
            }
        }
        return 0;
    },
    ispermanent: function(id){
        //这里的程序有点弱智，只考虑了两层目录，如果多级别，需要用类似递归的方法寻找
        ret = false;
        if (id == -1) 
            return true;
        udisk.res.each(function(item){
            if (parseInt(item.id) == parseInt(id) && parseInt(item.parentid) == -1) {
                ret = true;
            }
        });
        return ret;
    },
    getNodeById: function(id){
        var m = this.datam;
        var length = m.length;
        var low = 0;
        var high = length;
        var pointer = parseInt((low + high) / 2);
        for (var i = 0; i < m.length; i++) {
            if (low == high && parseInt(m[pointer].id) != id) 
                return null;
            if (parseInt(m[pointer].id) == id) {
                return m[pointer];
            }
            if (parseInt(m[pointer].id) < id) {
                low = pointer;
            }
            if (parseInt(m[pointer].id) > id) {
                high = pointer;
            }
            pointer = parseInt((low + high) / 2);
        }
        return null;
    }
    
};
var udisk = new UDisk();


